package com.xudow.app.ui;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;

import com.xudow.app.R;
import com.xudow.app.XApplication;
import com.xudow.app.ui.widget.TitleBarTextView;
import com.xudow.app.util.WebViewUtils;

import org.apache.http.client.CookieStore;
import org.apache.http.cookie.Cookie;

import java.util.List;

/**
 * 地图网页浏览Activity
 *
 * @author lukecheng
 */
public class MapViewActivity extends BaseActivity {

    private RelativeLayout progressLayout;
    private WebView webView;
    private TitleBarTextView titleBarTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map_view);

        progressLayout = (RelativeLayout) findViewById(R.id.progressbar);
        webView = (WebView) findViewById(R.id.webview);
        titleBarTextView = (TitleBarTextView) findViewById(R.id.title);

        Intent intent = getIntent();
        String url = intent.getStringExtra("url");

        XApplication application = (XApplication) getApplication();
        CookieStore cookieStore = application.getCookieStore();
        if (null != cookieStore) {
            List<Cookie> cookies = cookieStore.getCookies();

            if (null != cookies) {
                String cookie = "";

                for (Cookie c : cookies) {
                    if ("JSESSIONID".equalsIgnoreCase(c.getName())) {
                        cookie = "JSESSIONID=" + c.getValue() + ";Path=" + c.getPath() + ";HttpOnly";
                        break;
                    }
                }

                WebViewUtils.synCookies(this, url, cookie);
            }
        }

        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);

                progressLayout.setVisibility(View.GONE);
                webView.setVisibility(View.VISIBLE);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;
            }
        });
        
        webView.loadUrl(url);
    }

    public void onBackBtnClick(View view) {
        finish();
    }
}
